<template>
  <div class="refund-container">
    <h1>窗口退号</h1>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="挂号详情"
      width="700px"
      :before-close="handleClose"
    >
      <div class="detail-info" v-if="currentRegister">
        <el-row :gutter="20">
          <el-col :span="12">
            <p><strong>病历号：</strong>{{ currentRegister.caseNumber }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>姓名：</strong>{{ currentRegister.realName }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>看诊医生：</strong>{{ currentRegister.employeeName || '未知医生' }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>看诊科室：</strong>{{ currentRegister.deptmentName || '未知科室' }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>看诊状态：</strong>{{ getStatusText(currentRegister.visitState) }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>挂号日期：</strong>{{ currentRegister.visitDate }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>挂号费用：</strong>{{ currentRegister.registerFee || '0' }}元</p>
          </el-col>
          <el-col :span="12">
            <p><strong>午别：</strong>{{ currentRegister.noon || '未知' }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>结算类别：</strong>{{ currentRegister.settleCategoryName || '未知' }}</p>
          </el-col>
          <el-col :span="12">
            <p><strong>挂号时间：</strong>{{ currentRegister.createTime || '未知' }}</p>
          </el-col>
          <el-col :span="24">
            <p><strong>备注：</strong>{{ currentRegister.remark || '无' }}</p>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 精准搜索区域 -->
    <div class="search-section">
      <h3>精准搜索</h3>
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="病历号：">
          <el-input v-model="searchForm.caseNumber" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input v-model="searchForm.realName" placeholder="请输入病人名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按条件筛选区域 -->
    <div class="filter-section">
      <h3>按条件筛选</h3>
      <el-form :model="filterForm" label-width="120px" inline>
        <el-form-item label="看诊状态：">
          <el-select v-model="filterForm.visitState" placeholder="请选择" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="未开始" value="1" />
            <el-option label="进行中" value="2" />
            <el-option label="已看诊" value="3" />
            <el-option label="已退号" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号日期：">
          <el-date-picker
            v-model="filterForm.visitDateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="看诊科室：">
          <el-select v-model="filterForm.deptmentId" placeholder="请选择" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="内科" value="1" />
            <el-option label="外科" value="2" />
            <el-option label="儿科" value="3" />
            <el-option label="妇产科" value="4" />
            <el-option label="眼科" value="5" />
            <el-option label="心血管" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 已选择项和统计信息 -->
    <div class="selected-section" v-if="selectedCount > 0">
      <div class="selected-info">
        <i class="el-icon-info"></i>
        已选择 <span class="selected-count">{{ selectedCount }}</span> 项
        <el-button type="text" class="clear-btn" @click="clearSelection">清空</el-button>
      </div>
    </div>

    <!-- 挂号信息列表 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="registerList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="55" 
          :selectable="canSelectRow"  
        />
        <el-table-column prop="caseNumber" label="病历号" width="120" />
        <el-table-column prop="realName" label="姓名" width="120" />
        <el-table-column prop="employeeName" label="看诊医生" width="120" />
        <el-table-column prop="visitState" label="看诊状态" width="120">
          <template #default="scope">
            <div class="status-dot" :class="getStatusClass(scope.row.visitState)"></div>
            <span>{{ getStatusText(scope.row.visitState) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="visitDate" label="挂号日期" width="180" />
        <el-table-column prop="deptmentName" label="看诊科室" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              type="text" 
              class="refund-btn"
              @click="handleRefund(scope.row)"
              :disabled="!canRefund(scope.row.visitState)"
            >
              退号
            </el-button>
            <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-section">
        <el-button type="primary" @click="handleBatchRefund" :disabled="selectedCount === 0">批量退号</el-button>
        <div class="pagination-controls">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus'
import registerApi from '@/api/register.js'
import request from '@/utils/request'

// 搜索表单
const searchForm = reactive({
  caseNumber: '',
  realName: ''
})

// 筛选表单
const filterForm = reactive({
  visitState: '',
  visitDateRange: [], // 初始化为空，不默认传递时间参数
  deptmentId: ''
})

// 挂号列表数据
const registerList = ref([])
const loading = ref(false)
const selectedRowKeys = ref([])
const selectedCount = computed(() => selectedRowKeys.value.length)
const totalCount = ref(0) // 服务调用总计

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const dialogVisible = ref(false)
const currentRegister = ref(null)
const canSelectRow = (row) => {
  // 只有"未开始"状态（值为1）的行可以被选择
  return row.visitState === 1;
}
// 获取挂号列表数据
const getRegisterList = async () => {
  loading.value = true;
  try {
    // 整合搜索条件和筛选条件作为请求参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      caseNumber: searchForm.caseNumber,
      realName: searchForm.realName,
      visitState: filterForm.visitState,
      deptmentId: filterForm.deptmentId
    };
    
    // 添加日期范围参数
    if (filterForm.visitDateRange && filterForm.visitDateRange.length === 2) {
      params.startDate = filterForm.visitDateRange[0];
      params.endDate = filterForm.visitDateRange[1];
    }
    
    console.log('请求参数:', params);
    console.log('请求URL:', '/registers/page');
    
    // 调用api模块中的getByPage方法，传入搜索和筛选参数
    const response = await registerApi.getByPage(params);
    
    // 检查响应是否存在
    if (!response) {
      ElMessage.error('未收到服务器响应');
      return;
    }
    
    // 根据实际接口返回结构调整数据处理逻辑
    console.log('响应数据:', response);
    
    // 处理axios拦截器返回的格式
    if (response.success || response.code === 200) {
      // 检查是否是分页格式的响应
      if (response.list !== undefined) {
        // 处理分页格式
        registerList.value = response.list.map(item => ({
          ...item,
          employeeName: item.employeeName || '未知医生',  
          deptmentName: item.deptmentName || '未知科室',
          visitState: item.visitState || 1, // 确保有状态值
          caseNumber: item.caseNumber || '', // 确保有病历号
          realName: item.realName || '' // 确保有姓名
        }));
        pagination.total = response.total || 0;
      } else if (Array.isArray(response) || Array.isArray(response.data)) {
        // 处理直接返回数组或在data字段中的数组
        const dataArray = Array.isArray(response) ? response : response.data;
        registerList.value = dataArray.map(item => ({
          ...item,
          employeeName: item.employeeName || '未知医生',  
          deptmentName: item.deptmentName || '未知科室',
          visitState: item.visitState || 1, // 确保有状态值
          caseNumber: item.caseNumber || '', // 确保有病历号
          realName: item.realName || '' // 确保有姓名
        }));
        // 由于后端分页接口没有返回总数，我们需要额外调用count接口
        const countResponse = await registerApi.countAll();
        if (countResponse.success || (countResponse.code === 200 && countResponse.data)) {
          pagination.total = countResponse.data || countResponse.total || 0;
        }
      } else {
        ElMessage.warning('获取挂号数据格式不符合预期');
        registerList.value = [];
        pagination.total = 0;
      }
    } else {
      ElMessage.warning(response.message || '获取挂号数据失败');
      registerList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取挂号列表失败:', error);
    // 更详细的错误信息
    if (error.response) {
      console.error('错误状态码:', error.response.status);
      console.error('错误响应:', error.response.data);
    }
    ElMessage.error('网络错误，请重试');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getRegisterList()
}

// 处理筛选
const handleFilter = () => {
  pagination.currentPage = 1
  getRegisterList()
}

// 重置搜索表单
const resetSearch = () => {
  searchForm.caseNumber = ''
  searchForm.realName = ''
}

// 重置筛选表单
const resetFilter = () => {
  filterForm.visitState = ''
  filterForm.visitDateRange = [] // 重置为空，不默认传递时间参数
  filterForm.deptmentId = ''
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRowKeys.value = selection.map(item => item.id)
}

// 清空选择
const clearSelection = () => {
  selectedRowKeys.value = []
}

// 处理退号
const handleRefund = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要为${row.realName}（病历号：${row.caseNumber}）办理退号吗？`,
      '退号确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端退号接口
    const response = await request.delete(`/registers/${row.id}`)
    
    if (response.code === 200) {
      ElMessage.success('退号成功')
      getRegisterList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '退号失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退号失败:', error)
      ElMessage.error('网络错误，请重试')
    }
  }
}

// 处理批量退号
const handleBatchRefund = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要退号的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要为选中的${selectedRowKeys.value.length}条记录办理退号吗？`,
      '批量退号确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端批量退号接口
    const response = await request.post('/registers/batch-refund', selectedRowKeys.value)
        
    if (response.code === 200) {
      ElMessage.success('批量退号成功')
      clearSelection()
      getRegisterList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '批量退号失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量退号失败:', error)
      ElMessage.error('网络错误，请重试')
    }
  }
}

// 查看详情
const handleView = (row) => {
  currentRegister.value = row
  dialogVisible.value = true
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  currentRegister.value = null
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '未开始',
    2: '进行中',
    3: '已看诊',
    4: '已退号',
    5: '过期'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: 'status-not-started',
    2: 'status-in-progress',
    3: 'status-completed',
    4: 'status-refunded',
    5: 'status-expired'
  }
  return classMap[status] || ''
}

// 判断是否可以退号
const canRefund = (status) => {
  // 假设只有未开始的挂号可以退号
  return status === 1
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getRegisterList()
}

// 当前页码变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  getRegisterList()
}

// 初始加载数据
onMounted(() => {
  getRegisterList()
  // 模拟服务调用总计数据
  // totalCount.value = '36.4万'
})
</script>

<style scoped>
.refund-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.search-section,
.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-section h3,
.filter-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.selected-section {
  margin-bottom: 15px;
}

.selected-info {
  padding: 10px 15px;
  background-color: #e6f7ff;
  border-left: 4px solid #1890ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.selected-count {
  color: #1890ff;
  font-weight: 600;
  margin: 0 2px;
}

.total-count {
  color: #1890ff;
  font-weight: 600;
  margin: 0 2px;
}

.clear-btn {
  margin-left: 15px;
  color: #909399;
}

.table-section {
  margin-bottom: 20px;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
  vertical-align: middle;
}

.status-not-started {
  background-color: #dcdfe6;
}

.status-in-progress {
  background-color: #409eff;
}

.status-completed {
  background-color: #67c23a;
}

.status-refunded {
  background-color: #909399;
}

.status-expired {
  background-color: #f56c6c;
}

.refund-btn {
  color: #1890ff;
}

.refund-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-controls {
  display: flex;
  justify-content: flex-end;
}
</style>